//
//  AgreementView.m
//  Cycling
//
//  Created by cjg.mini on 2023/5/12.
//

#import "AgreementView.h"
#import "CycLabel.h"
#import "UserModel.h"
#import <WebKit/WebKit.h>

@interface AgreementView()<WKNavigationDelegate>

@property (nonatomic, strong)UIView *bgCoverMaskView;
@property (nonatomic, strong)CycLabel *titleLabel;
@property (nonatomic, strong)CycLabel *agreementLabel;
@property (nonatomic, strong)UIButton *okBtn;
@property (nonatomic, strong)UIButton *cancleBtn;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) WKWebView *webView;

@property (nonatomic, copy)void(^okActionBlock)(void);
@property (nonatomic, copy)void(^CancleActionBlock)(void);

@end

@implementation AgreementView

static AgreementView *alertView = nil;

+ (instancetype)instanceAgreementView {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        alertView = [[AgreementView alloc] init];
        });
    return alertView;

}

- (instancetype)init {
    return [self initWithFrame:CGRectMake(0, 160, SCREEN_W, SCREEN_H - 160)];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = COLOR_WHITE;
    }
    return self;
}
- (WKWebView *)webView {
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero];
        _webView.navigationDelegate = self;
        
    }
    return _webView;
//    WKWebView* webView = [[NSClassFromString(@"WKWebView") alloc] initWithFrame:CGRectZero];
//    [webView setOpaque:NO];
//    webView.navigationDelegate = self;
//    webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//    [self loadExamplePage:webView];

//    [self.view addSubview:webView];
}
- (CycLabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[CycLabel alloc] init];
        _titleLabel.font = FONT_PRIMARY_TITLE;
        _titleLabel.textColor = COLOR_BLACK;
        _titleLabel.numberOfLines = 0;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.preferredMaxLayoutWidth = SCREEN_W-BLANK_20*2;
        [_titleLabel setContentHuggingPriority:UILayoutPriorityRequired
                                 forAxis:UILayoutConstraintAxisVertical];
    }
    return _titleLabel;
}

-(CycLabel *)agreementLabel {
    if (!_agreementLabel) {
        _agreementLabel = [[CycLabel alloc] init];
        _agreementLabel.font = FONT_BODY_16;
        _agreementLabel.textColor = COLOR_SIMPLEBLACK;
        _agreementLabel.numberOfLines = 0;
        _agreementLabel.textAlignment = NSTextAlignmentLeft;

//        _agreementLabel.preferredMaxLayoutWidth = SCREEN_W-BLANK_20*2;
        [_agreementLabel setContentHuggingPriority:UILayoutPriorityRequired
                                 forAxis:UILayoutConstraintAxisVertical];
    }
    return _agreementLabel;
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '350%'" completionHandler:nil];
    
    // 设置字体
    NSString *fontFamilyStr = @"document.getElementsByTagName('body')[0].style.fontFamily='PingFangSC-Semibold';";
    [webView evaluateJavaScript:fontFamilyStr completionHandler:nil];
    // 设置字体大小
    NSString *fontSizeStr = @"document.getElementsByTagName('section')[0].style.fontSize='22px';";
    [webView evaluateJavaScript:fontSizeStr completionHandler:nil];
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

-(UIButton *)okBtn {
    if (!_okBtn) {
        _okBtn = [[UIButton alloc] init];
        [_okBtn setTitle:@"同意" forState:(UIControlStateNormal)];
        [_okBtn setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
        _okBtn.backgroundColor = COLOR_TOPIC_SELECT;
        _okBtn.layer.cornerRadius = 27;
        _okBtn.layer.masksToBounds = YES;
        [_okBtn addTarget:self action:@selector(okBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _okBtn;
}

-(UIButton *)cancleBtn {
    if (!_cancleBtn) {
        _cancleBtn = [[UIButton alloc] init];
        [_cancleBtn setTitle:@"不同意" forState:(UIControlStateNormal)];
        [_cancleBtn setTitleColor:COLOR_OFFLINE forState:UIControlStateNormal];
        _cancleBtn.backgroundColor = [UIColor clearColor];
        [_cancleBtn addTarget:self action:@selector(cancleBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _cancleBtn;
}

- (void)okBtnAction:(UIButton *)sender {
    if (self.okActionBlock) {
        self.okActionBlock();
    }
    [USERDEFAULTS setBool:YES forKey:[NSString stringWithFormat:@"kSureAgreement_%ld",(long)UserModel.currentUserInfo.user_id]];
    [self dismissAgreementView];
}

- (void)cancleBtnAction:(UIButton *)sender {
    if (self.CancleActionBlock) {
        self.CancleActionBlock();
    }
    [self dismissAgreementView];
}

- (void)showAgreementViewWithTitles:(NSString *)title description:(NSString *)description ok:(NSString *__nullable)ok okBlock:(void(^ __nullable)(void))okBlock cancle:(NSString *__nullable)cancle cancleBlock:(void(^ __nullable)(void))cancleBlock {
    self.titleLabel.text = title;
    
    [self.webView loadHTMLString:description baseURL:nil];
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[description dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    self.agreementLabel.font = FONT_BODY_16;
    self.agreementLabel.attributedText = attrStr;
    [self.okBtn setTitle:ok forState:(UIControlStateNormal)];
    [self.cancleBtn setTitle:cancle forState:(UIControlStateNormal)];
    self.okActionBlock = okBlock;
    self.CancleActionBlock = cancleBlock;
    [self setUpAleartUIWithTitle:title message:description];
    [self showAlertView];
}
- (void)setUpAleartUIWithTitle:(NSString *)title message:(NSString *)message {
    CGFloat titleHeight = [CycLabel heightForString:title font:FONT_PRIMARY_TITLE andWidth:SCREEN_W - BLANK_20*2];
    CGFloat messageHeight = [message boundingRectWithSize:CGSizeMake(SCREEN_W - BLANK_20*2, MAXFLOAT) options:nil attributes:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } context:nil].size.height;

    [self addSubview:self.titleLabel];
    [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(19);
        make.left.equalTo(self).offset(MARGIN_MAX);
        make.right.equalTo(self).offset(-MARGIN_MAX);
        make.height.mas_offset(titleHeight);
    }];
//    self.scrollView.contentSize = CGSizeMake(SCREEN_W - MARGIN_MAX * 2, messageHeight + 10);
    [self addSubview:self.webView];
    [self.webView mas_updateConstraints:^(MASConstraintMaker *make) {
        if(title && title.length){
            make.top.equalTo(self.titleLabel.mas_bottom).offset(BLANK_10);
        }else{
            make.top.equalTo(self).offset(19);
        }
        make.left.equalTo(self).offset(MARGIN_MAX);
        make.right.equalTo(self).offset(-MARGIN_MAX);
        make.bottom.equalTo(self.mas_bottom).offset(- 140);
    }];

//    [self.scrollView addSubview:self.agreementLabel];
//    [self.agreementLabel mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.scrollView.mas_top);
//        make.left.equalTo(self).offset(MARGIN_MAX);
//        make.right.equalTo(self).offset(-MARGIN_MAX);
//        make.height.mas_offset(messageHeight);
//    }];
    
    [self addSubview:self.okBtn];
    [self.okBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.webView.mas_bottom).offset(MARGIN_MIDDLE);
        make.right.equalTo(self).offset(-MARGIN_MAX);
        make.left.equalTo(self).offset(MARGIN_MAX);
        make.height.mas_offset(54);
    }];
    
    [self addSubview:self.cancleBtn];
    [self.cancleBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.okBtn.mas_bottom).offset(MARGIN_MIDDLE);
        make.right.equalTo(self).offset(-MARGIN_MAX);
        make.left.equalTo(self).offset(MARGIN_MAX);
        make.height.mas_offset(54);
    }];
    
//    CGRect frame = self.frame;
//    frame.size.height = 54*2+20 + messageHeight + titleHeight + 19 + ((title && title.length)?BLANK_10:0);
//    frame.origin.y = SCREEN_H - frame.size.height;
//    self.frame = frame;
    // 切圆角
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(20, 20)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;

//    NSLog(@"%f =========%f============ %f",frame.size.height,self.frame.size.height,messageHeight);
}

- (void)showAlertView {
    UIWindow *window = [self mainWindow];
    if (!_bgCoverMaskView) {
        _bgCoverMaskView = [[UIControl alloc] initWithFrame:window.bounds];
        _bgCoverMaskView.backgroundColor = COLOR_SHADE;
    }
    [window addSubview:_bgCoverMaskView];
    [window addSubview:self];

    self.alpha = 0;
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:.3 delay:0 usingSpringWithDamping:.5 initialSpringVelocity:.5 options:0 animations:^{
        weakSelf.alpha = 1;
    } completion:^(BOOL finished) {
        if (finished) {
        }
    }];
}

- (void)dismissAgreementView {
    [self endEditing:YES];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];

    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:.3 animations:^{
        weakSelf.alpha = 0;
    } completion:^(BOOL finished) {
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf->_bgCoverMaskView removeFromSuperview];
        strongSelf->_bgCoverMaskView = nil;
        [weakSelf removeFromSuperview];
    }];
}

//获取当前的window
- (UIWindow *)mainWindow {
    UIApplication *app = [UIApplication sharedApplication];
    return app.keyWindow;
}

@end
